package com.im323.dnspod;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;

import com.fasterxml.jackson.databind.JsonNode;
import com.im323.common.util.DateUtil;
import com.im323.common.util.HttpClientUtils;
import com.im323.common.util.JsonUtil;
import com.im323.dnspod.result.DnspodDomain;
import com.im323.dnspod.result.DnspodRecord;
import com.im323.dnspod.result.DnspodRecordLine;
import com.im323.dnspod.result.DnspodResult;
import com.im323.dnspod.result.DnspodResultStatus;
import com.im323.dnspod.result.DnspodUser;
import com.im323.quartz.UpdateRecordModel;

public class DnspodService {

	private static Map<String, String> baseParams = new HashMap<>();

	static {
		initBaseParam(null);
	}

	public static void initBaseParam(String token) {
		baseParams.put("login_token", token);
		baseParams.put("format", "json");
		baseParams.put("lang", "cn");
	}

	/**
	 * 获取用户账户信息
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月18日下午2:48:04
	 */
	public static DnspodResult<DnspodUser> getUserDetail() {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.USER_DETAIL, param);
		DnspodResult<DnspodUser> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			JsonNode infoNode = rootNode.get("info");
			if (infoNode != null) {
				JsonNode userNode = infoNode.get("user");
				if (userNode != null) {
					String real_name = userNode.get("real_name").textValue();
					String user_type = userNode.get("user_type").textValue();
					String telephone = userNode.get("telephone").textValue();
					String nick = userNode.get("nick").textValue();
					String id = userNode.get("id").textValue();
					String email = userNode.get("email").textValue();
					String status = userNode.get("status").textValue();
					String email_verified = userNode.get("email_verified").textValue();
					String telephone_verified = userNode.get("telephone_verified").textValue();
					String weixin_binded = userNode.get("weixin_binded").textValue();
					String agent_pending = userNode.get("agent_pending").textValue();
					String balance = userNode.get("balance").textValue();
					String smsbalance = userNode.get("smsbalance").textValue();
					String user_grade = userNode.get("user_grade").textValue();

					DnspodUser dnspodUser = new DnspodUser();
					dnspodUser.setRealName(real_name);
					dnspodUser.setUserType(user_type);
					dnspodUser.setTelePhone(telephone);
					dnspodUser.setNick(nick);
					dnspodUser.setId(id);
					dnspodUser.setEmail(email);
					dnspodUser.setStatus(status);
					dnspodUser.setEmailVerified("no".equalsIgnoreCase(email_verified) ? false : true);
					dnspodUser.setTelePhoneVerifed("no".equalsIgnoreCase(telephone_verified) ? false : true);
					dnspodUser.setWeixinBinded("no".equals(weixin_binded) ? false : true);
					dnspodUser.setAgentPending("no".equals(agent_pending) ? false : true);
					dnspodUser.setBalance(NumberUtils.toFloat(balance));
					dnspodUser.setSmsbalance(NumberUtils.toFloat(smsbalance));
					dnspodUser.setUserGrade(user_grade);

					result.setInfo(dnspodUser);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 查询域名列表
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月24日上午11:53:35
	 */
	public static DnspodResult<List<DnspodDomain>> getDomainList() {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.DOMAIN_LIST, param);
		DnspodResult<List<DnspodDomain>> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			JsonNode infoNode = rootNode.get("domains");
			if (infoNode != null) {
				List<DnspodDomain> dnspodDomains = new ArrayList<>();
				for (Iterator<JsonNode> iterator = infoNode.iterator(); iterator.hasNext();) {
					JsonNode domainNode = (JsonNode) iterator.next();

					Integer id = domainNode.get("id").intValue();
					String status = domainNode.get("status").textValue();
					String grade = domainNode.get("grade").textValue();
					String group_id = domainNode.get("group_id").textValue();
					String searchengine_push = domainNode.get("searchengine_push").textValue();
					String is_mark = domainNode.get("is_mark").textValue();
					String ttl = domainNode.get("ttl").textValue();
					String cname_speedup = domainNode.get("cname_speedup").textValue();
					String remark = domainNode.get("remark").textValue();
					String created_on = domainNode.get("created_on").textValue();
					String updated_on = domainNode.get("updated_on").textValue();
					String punycode = domainNode.get("punycode").textValue();
					String ext_status = domainNode.get("ext_status").textValue();
					String name = domainNode.get("name").textValue();
					String grade_title = domainNode.get("grade_title").textValue();
					String is_vip = domainNode.get("is_vip").textValue();
					String owner = domainNode.get("owner").textValue();
					String records = domainNode.get("records").textValue();

					String auth_to_anquanbao = null;
					if (domainNode.get("auth_to_anquanbao") != null) {
						auth_to_anquanbao = domainNode.get("auth_to_anquanbao").textValue();
					}

					DnspodDomain dnspodDomain = new DnspodDomain();
					dnspodDomains.add(dnspodDomain);

					dnspodDomain.setId(id);
					dnspodDomain.setStatus(status);
					dnspodDomain.setGrade(grade);
					dnspodDomain.setGroupId(group_id);
					dnspodDomain.setSearchengine_push(searchengine_push);
					dnspodDomain.setIsMark(is_mark);
					dnspodDomain.setTtl(ttl);
					dnspodDomain.setCnameSpeedup(cname_speedup);
					dnspodDomain.setRemark(remark);
					dnspodDomain.setCreatedOn(DateUtil.string2Date(created_on, "yyyy-MM-dd HH:mm:ss"));
					dnspodDomain.setUpdatedOn(DateUtil.string2Date(updated_on, "yyyy-MM-dd HH:mm:ss"));
					dnspodDomain.setPunycode(punycode);
					dnspodDomain.setExtStatus(ext_status);
					dnspodDomain.setName(name);
					dnspodDomain.setGradeTitle(grade_title);
					dnspodDomain.setIsVip(is_vip);
					dnspodDomain.setOwner(owner);
					dnspodDomain.setRecords(records);
					dnspodDomain.setAuthToAnquanbao(auth_to_anquanbao);
				}
				result.setInfo(dnspodDomains);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 查询记录列表
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月24日上午11:53:44
	 */
	public static DnspodResult<List<DnspodRecord>> getRecordList(Integer domainId) {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		param.put("domain_id", String.valueOf(domainId));
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.RECORD_LIST, param);
		DnspodResult<List<DnspodRecord>> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			JsonNode recordsNode = rootNode.get("records");
			if (recordsNode != null) {
				List<DnspodRecord> dnsRecords = new ArrayList<>();
				for (Iterator<JsonNode> iterator = recordsNode.iterator(); iterator.hasNext();) {
					JsonNode recordNode = (JsonNode) iterator.next();

					Integer id = recordNode.get("id").asInt();
					String name = recordNode.get("name").textValue();
					String line = recordNode.get("line").textValue();
					String line_id = recordNode.get("line_id").textValue();
					String type = recordNode.get("type").textValue();
					Integer ttl = recordNode.get("ttl").asInt();
					String value = recordNode.get("value").textValue();
					Integer mx = recordNode.get("mx").asInt();
					Integer enabled = recordNode.get("enabled").asInt();
					String status = recordNode.get("status").textValue();
					String monitor_status = recordNode.get("monitor_status").textValue();
					String remark = recordNode.get("remark").textValue();
					String updated_on = recordNode.get("updated_on").textValue();
					String use_aqb = recordNode.get("use_aqb").textValue();

					DnspodRecord dnspodRecord = new DnspodRecord();
					dnsRecords.add(dnspodRecord);

					dnspodRecord.setId(id);
					dnspodRecord.setName(name);
					dnspodRecord.setLine(line);
					dnspodRecord.setLine_id(line_id);
					dnspodRecord.setType(type);
					dnspodRecord.setTtl(ttl);
					dnspodRecord.setValue(value);
					dnspodRecord.setMx(mx);
					dnspodRecord.setEnabled(enabled == 1 ? true : false);
					dnspodRecord.setStatus(status);
					dnspodRecord.setMonitorStatus(monitor_status);
					dnspodRecord.setRemark(remark);
					dnspodRecord.setUpdatedOn(DateUtil.string2Date(updated_on, "yyyy-MM-dd HH:mm:ss"));
					dnspodRecord.setUseAqb("yes".equals(use_aqb) ? true : false);

				}
				result.setInfo(dnsRecords);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 更新动态记录
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月24日下午5:29:44
	 */
	public static DnspodResult<DnspodRecord> updateDDNS(UpdateRecordModel updateRecordModel) {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		param.put("domain_id", String.valueOf(updateRecordModel.getDomainId()));
		param.put("record_id", String.valueOf(updateRecordModel.getRecordId()));
		param.put("sub_domain", updateRecordModel.getSubDomain());
		param.put("record_line_id", updateRecordModel.getRecordLineId());
		param.put("value", updateRecordModel.getValue());
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.RECORD_DDNS, param);
		DnspodResult<DnspodRecord> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			JsonNode recordNode = rootNode.get("record");
			if (recordNode != null) {
				Integer id = recordNode.get("id").intValue();
				String name = recordNode.get("name").textValue();
				String value = recordNode.get("value").textValue();

				DnspodRecord dnspodRecord = new DnspodRecord();
				result.setInfo(dnspodRecord);

				dnspodRecord.setId(id);
				dnspodRecord.setName(name);
				dnspodRecord.setValue(value);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 域名等级, 分别为： 旧套餐：D_Free、D_Plus、D_Extra、D_Expert、D_Ultra
	 * 分别对应免费套餐、个人豪华、企业1、企业2、企业3 新套餐：DP_Free、DP_Plus、DP_Extra、DP_Expert、DP_Ultra
	 * 分别对应新免费、个人专业版、企业创业版、企业标准版、企业旗舰版
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月25日下午4:36:28
	 */
	public static DnspodResult<List<String>> getRecordType(String domain_grade) {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		param.put("domain_grade", domain_grade);
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.RECORD_TYPE, param);
		DnspodResult<List<String>> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			List<String> list = new ArrayList<>();
			result.setInfo(list);
			JsonNode typesNode = rootNode.get("types");
			if (typesNode != null) {
				for (int i = 0; i < typesNode.size(); i++) {
					list.add(typesNode.get(i).textValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取等级允许的线路
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月25日下午4:42:32
	 */
	public static DnspodResult<List<DnspodRecordLine>> getRecordLine(Integer domainId, String domain_grade) {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		param.put("domain_id", String.valueOf(domainId));
		param.put("domain_grade", domain_grade);
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.RECORD_LINE, param);
		DnspodResult<List<DnspodRecordLine>> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			List<DnspodRecordLine> list = new ArrayList<>();
			result.setInfo(list);

			// 解析线路
			JsonNode linesNode = rootNode.get("lines");
			if (linesNode != null) {
				for (int i = 0; i < linesNode.size(); i++) {
					String lineName = linesNode.get(i).textValue();
					DnspodRecordLine dnspodRecordLine = new DnspodRecordLine();
					dnspodRecordLine.setLineName(lineName);
					list.add(dnspodRecordLine);
				}
			}

			// 解析线路id
			JsonNode lineIdsNode = rootNode.get("line_ids");
			if (lineIdsNode != null) {
				for (int i = 0; i < list.size(); i++) {
					JsonNode lineIdNode = lineIdsNode.get(list.get(i).getLineName());
					if (lineIdNode != null) {
						list.get(i).setLineId(lineIdNode.asText());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 修改记录
	 * 
	 * @description
	 * @author 王璞
	 * @date 2017年10月25日下午6:23:49
	 */
	public static DnspodResult<DnspodRecord> editRecord(Integer domainId, Integer recordId, DnspodRecord dnspodRecord) {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		param.put("domain_id", String.valueOf(domainId));
		if (recordId != null) {
			param.put("record_id", String.valueOf(recordId));
		}
		param.put("sub_domain", dnspodRecord.getName());
		param.put("record_type", dnspodRecord.getType());
		param.put("record_line_id", dnspodRecord.getLine_id());
		param.put("value", dnspodRecord.getValue());
		if (dnspodRecord.getMx() != null) {
			param.put("mx", String.valueOf(dnspodRecord.getMx()));
		}
		if (dnspodRecord.getTtl() != null) {
			param.put("ttl", String.valueOf(dnspodRecord.getTtl()));
		}
		if (dnspodRecord.isEnabled() != null && !dnspodRecord.isEnabled()) {
			param.put("status", "disable");
		}
		if (dnspodRecord.getWeight() != null) {
			param.put("weight", String.valueOf(dnspodRecord.getWeight()));
		}
		String url = DnspodHttpInterface.RECORD_MODIFY;
		if (recordId == null) {
			url = DnspodHttpInterface.RECORD_CREATE;
		}
		String doPost = HttpClientUtils.doPost(url, param);
		DnspodResult<DnspodRecord> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			DnspodRecord dRecord = new DnspodRecord();
			result.setInfo(dRecord);

			// 解析线路
			JsonNode recordNode = rootNode.get("record");
			if (recordNode != null) {
				int id = recordNode.get("id").intValue();
				String name = recordNode.get("name").textValue();
				String value = recordNode.get("value").textValue();
				String status = recordNode.get("status").textValue();

				dRecord.setId(id);
				dRecord.setName(name);
				dRecord.setValue(value);
				dRecord.setEnabled("enable".equals(status) ? true : false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取解析记录详情
	 * 
	 * @param domainId
	 * @param recordId
	 * @return
	 */
	public static DnspodResult<DnspodRecord> getRecordInfo(Integer domainId, Integer recordId) {
		Map<String, String> param = new HashMap<>();
		param.putAll(baseParams);
		param.put("domain_id", String.valueOf(domainId));
		param.put("record_id", String.valueOf(recordId));
		String doPost = HttpClientUtils.doPost(DnspodHttpInterface.RECORD_INFO, param);
		DnspodResult<DnspodRecord> result = new DnspodResult<>();
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doPost);
			JsonNode statusNode = rootNode.get("status");

			DnspodResultStatus dnspodResultStatus = new DnspodResultStatus();

			String message = statusNode.get("message").textValue();
			String created_at = statusNode.get("created_at").textValue();

			dnspodResultStatus.setCode(statusNode.get("code").asInt());
			dnspodResultStatus.setMessage(message);
			dnspodResultStatus.setCreateTime(DateUtil.string2Date(created_at, "yyyy-MM-dd HH:mm:ss"));

			result.setStatus(dnspodResultStatus);

			// 解析线路
			JsonNode recordNode = rootNode.get("record");
			if (recordNode != null) {
				Integer id = recordNode.get("id").asInt();
				String sub_domain = recordNode.get("sub_domain").textValue();
				String line = recordNode.get("record_line").textValue();
				String line_id = recordNode.get("record_line_id").textValue();
				String type = recordNode.get("record_type").textValue();
				Integer ttl = recordNode.get("ttl").asInt();
				String value = recordNode.get("value").textValue();
				Integer mx = recordNode.get("mx").asInt();
				Integer enabled = recordNode.get("enabled").asInt();
				String monitor_status = recordNode.get("monitor_status").textValue();
				String remark = recordNode.get("remark").textValue();
				String updated_on = recordNode.get("updated_on").textValue();

				DnspodRecord dnspodRecord = new DnspodRecord();
				result.setInfo(dnspodRecord);

				dnspodRecord.setId(id);
				dnspodRecord.setName(sub_domain);
				dnspodRecord.setLine(line);
				dnspodRecord.setLine_id(line_id);
				dnspodRecord.setType(type);
				dnspodRecord.setTtl(ttl);
				dnspodRecord.setValue(value);
				dnspodRecord.setMx(mx);
				dnspodRecord.setEnabled(enabled == 1 ? true : false);
				dnspodRecord.setMonitorStatus(monitor_status);
				dnspodRecord.setRemark(remark);
				dnspodRecord.setUpdatedOn(DateUtil.string2Date(updated_on, "yyyy-MM-dd HH:mm:ss"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

}
